package club.pinea.server;

import club.pinea.pool.ProtoPoolExecutor;
import club.pinea.proto.BasicProto;
import club.pinea.proto.CommandProto;
import club.pinea.session.IOSession;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.Message;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.security.NoSuchAlgorithmException;

/**
 * @author pineapple
 * @date 2017年12月28日 上午10:11:40
 * @description 登录请求处理类
 */
@Component
@ChannelHandler.Sharable
public class LoginServerHandler extends SimpleChannelInboundHandler<BasicProto.BaseMessage> {

    private static Logger logger = LoggerFactory.getLogger(LoginServerHandler.class);

    @Autowired
    private ProtoPoolExecutor executor;

    /**
     * 处理客户端传入数据的方法
     */
    @Override
    protected void channelRead0(ChannelHandlerContext context, BasicProto.BaseMessage baseMessage) {
        logger.info("接收到客户端数据：" + baseMessage);
        IOSession session = createIOSession(context);
        executor.doTask(session, baseMessage);
    }

    private IOSession createIOSession(ChannelHandlerContext ctx) {
        IOSession session = new IOSession();
        session.setContext(ctx);
        session.setType(IOSession.SessionType.SOCKET);
        return session;
    }

    /**
     * 客户端未传入数据时自动关闭
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            if (((IdleStateEvent) evt).state() == IdleState.READER_IDLE) {
                ctx.close();
            }
        }
    }

}
